<?php

namespace app\index\service;

use app\admin\service\OssService;
use app\index\model\FileOss as FileOssModal;
use OSS\Core\OssException;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;
use OSS\Model\ServerSideEncryptionConfig;
use OSS\OssClient;

class Oss
{
    protected $ossClient;
    private $accessKeyId;
    private $accessKeySecret;
    private $endpoint;
    private $bucket;
    public function __construct(){
        $this->accessKeyId=config('oss.accessKeyId');
        $this->accessKeySecret=config('oss.accessKeySecret');
        $this->endpoint=config('oss.endpoint');
        $this->bucket=config('oss.bucket');

        $provider = new StaticCredentialsProvider(
            $this->accessKeyId,
            $this->accessKeySecret
        );
        $config = array(
            'region' => 'cn-hangzhou',
            'endpoint' => $this->endpoint,
            'provider' => $provider,
            'signatureVersion' => OssClient::OSS_SIGNATURE_VERSION_V4
        );
        $this->ossClient = new OssClient($config);
    }
    /**
     * 修改图片访问权限
     * @param $object string
     * @param $acl string default | public-read
     * @return boolean
     */
    public function setAlc($object, $acl = 'default')
    {
        $this->ossClient->putObjectAcl($this->bucket, $object, $acl);
        //  $acl = $client->getObjectAcl($bucket, $object);
        return true;
    }
    /**
     * 获取图片访问权限
     * @param $object string
     * @param $acl string default | public-read
     * @return string
     */
    public function getAlc($object)
    {
        $client = $this->ossClient;
        $bucket = $this->bucket;
        $acl = $client->getObjectAcl($bucket, $object);
        return $acl;
    }
    /**
     * 上传文件
     * @param $file
     * @param $alt string
     * @return array
     * @throws OssException
     */
    public function upload($file, $alt = '') {
        if($file->extension()) {
            $ext = $file->extension();
        } else {
            $ext = 'png';
        }
        $object = 'uploads/' . date('Ymd') . '/' . uniqid() . '.' . $ext;
        $timeout = 3600;
        $options = array(
            'Content-Type' => $this->getContentType($ext),
            OssClient::OSS_HEADERS => array(
                'Content-Disposition' => 'inline',
                'x-oss-meta-file-name' => $file->getOriginalName(),
            )
        );

        try {
            $signedUrl = $this->ossClient->signUrl($this->bucket, $object, $timeout, "PUT", $options);
            $request = new RequestCore($signedUrl);
            $request->set_method('PUT');
            $httpCore = new RequestCore($signedUrl);
            $httpCore->set_method('PUT');
            $request->add_header('Content-Type', $this->getContentType($ext));
            $request->add_header('Content-Disposition', 'inline');
            $request->add_header('x-oss-meta-file-name', $file->getOriginalName());
            $request->set_read_file($file);
            $request->set_read_stream_size(sprintf('%u', filesize($file)));
            $request->send_request();
            $res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());
            if($res->isOK()) {
                if($alt) {
                    $this->setAlc($object, $alt);
                }
                return [
                    'signedUrl' => $signedUrl,
                    'path' => $object
                ];
            } else {
                throw new \Error('上传失败');
            }
        } catch (OssException $e) {
            throw new \Error($e->getMessage());
        }
    }
    public function del($path) {
        $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
        $ossClient->deleteObject($this->bucket, $path);
    }

    public function sign($path) {
        $oss = new OssService();
        $signedUrl = $oss->signId($path);
        return $signedUrl;
    }

    protected function getContentType($extension)
    {
        $mimeTypes = [
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif'
        ];

        return $mimeTypes[$extension] ?? 'application/octet-stream';
    }
}